package com.ng.sys.service.impl;

import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ng.common.cache.annotation.TrCache;
import com.ng.common.redis.IFilter;
import com.ng.common.security.SecurityUtils;
import com.ng.common.service.CacheServiceImpl;
import com.ng.common.utils.PageUtils;
import com.ng.common.utils.Query;
import com.ng.sys.dao.SysDictDao;
import com.ng.sys.entity.SysDictEntity;
import com.ng.sys.service.SysDictService;


@Service("sysDictService")
public class SysDictServiceImpl extends  CacheServiceImpl<SysDictDao, SysDictEntity> implements SysDictService {

	@Autowired
	private SecurityUtils authUtils;
 
	 
	@Override
	@TrCache("'selectByTypeValue.' + #p0 + '.' + com.ng.common.utils.CollectionsUtils.collectionsToString(#p1)")
	public List<SysDictEntity> selectByTypeValue(String type, List<String> value) {
 
		QueryWrapper<SysDictEntity> wrapper = new QueryWrapper<>();
		wrapper.eq("type", type);
		wrapper.eq("delete_flag", 0);
		wrapper.in("value", value);
		
		
		List<SysDictEntity> list = this.list(wrapper);
		 
		
		return list ;
	}
	
	public PageUtils queryTypePage(String type , PageUtils page) {
		 IPage<SysDictEntity> ipage = baseMapper.queryPageList(page.getPage(SysDictEntity.class), type);
		return new PageUtils(ipage);
	}

	@Override
    public PageUtils queryPage(SysDictEntity entity , PageUtils page) {
    	
    	String type = entity.getType();
    	String name = entity.getName();
    	
    	QueryWrapper<SysDictEntity> wrapper = new QueryWrapper<>();
    	wrapper.eq("delete_flag", 0);
    	if(StringUtils.isNotBlank(type)) { 
    		wrapper.eq("type", type);
    		  
    	} // .or().like("dict_name", key).or().like("description", key);
    	if(StringUtils.isNotBlank(name)) { 
    		wrapper.like( "name" , name);
    	}
    	
        IPage<SysDictEntity> ipage = this.page(
                new Query<SysDictEntity>(page).getPage(),
                wrapper
                
        );

        return new PageUtils(ipage);
    }
 

  

	@Override
	@TrCache("'byTypeDictValue.' + #p0 + '.' + #p1")
	public SysDictEntity byTypeDictValue(String type, String value) {
 
		QueryWrapper<SysDictEntity> skuEntityWrappers = new QueryWrapper<>();
		skuEntityWrappers.eq("type",type).eq("value",value);
		skuEntityWrappers.eq("delete_flag", 0);
		SysDictEntity sysDictEntity = this.getOne(skuEntityWrappers,false);

		return sysDictEntity;
	}
	
	@Override
	public boolean save(SysDictEntity entity) {
		// TODO Auto-generated method stub
		if(entity.getCreateTime() == null) {
			entity.setCreateTime(new Date());
			entity.setUpdateTime(new Date());
		}
		
		if(StringUtils.isBlank(entity.getCreateId())) {
			
			String userId = authUtils.getCurrentUser().getUserId();
			
			entity.setCreateId(userId);
			entity.setUpdateId(userId);
		}
		entity.setDeleteFlag(0);
		// 清理此type的缓存
		clearTypeCache(entity.getType());
		 
		boolean result = super.save(entity);
	 
		return result ;
	}

	@Override
	//@TrCacheEvict("#className + '.' + #p0.dictId")
	public boolean updateById(SysDictEntity entity) {
		  
		entity.setUpdateTime(new Date());
	
		String userId =authUtils.getCurrentUser().getUserId();
	 

		entity.setUpdateId(userId);
		boolean result = super.updateById(entity);

		// 清理此type的缓存
		clearTypeCache(entity.getType());
		return result ;
	}

	@Override
	public void updateType(SysDictEntity entity) {
		// TODO Auto-generated method stub
		QueryWrapper<SysDictEntity> query = new QueryWrapper<>();
		query.eq("type", entity.getId());
		
		
		SysDictEntity update = new SysDictEntity();
		update.setType(entity.getType());
		update.setTypeName(entity.getTypeName());
		
		update(update, query);
		// 清理此type的缓存
		clearTypeCache(entity.getType());
	}
 
	@Override
	@TrCache("'findByType.' + #p0")
	public List<SysDictEntity> findByType(String type) {
 
    	QueryWrapper<SysDictEntity> wrapper = new QueryWrapper<>();
    	wrapper.eq("type", type);
    	wrapper.eq("delete_flag", 0);
    	List<SysDictEntity> list = list(wrapper);
    	 
    	
    	return list ;
	}
	
	@Override
	public boolean saveBatch(Collection<SysDictEntity> entityList, int batchSize) {
		clearCache();
		return super.saveBatch(entityList, batchSize);
	}

	@Override
	public String findByTypeAndValue(String type, String value) {
		StringBuffer stringBuffer = new StringBuffer();
		if (StringUtils.isNotBlank(value)){
			List<SysDictEntity> sysDictEntities = this.selectByTypeValue(type, Arrays.asList(value.split(",")));
			for (SysDictEntity dict : sysDictEntities) {
				stringBuffer.append(dict.getName()+",");
			}
		}
		if (stringBuffer.toString().length()==0){
			return "";
		}
		return stringBuffer.toString().substring(0,stringBuffer.toString().length()-1);
	}
	
	void clearTypeCache(String type) {
		// 清理此type的缓存
		String className = getClass().getSimpleName();
		redisUtils.deleteContains(type , new IFilter<String>() {

			@Override
			public boolean yes(String t) {
				// TODO Auto-generated method stub
				return t.startsWith(className);
			}
		});
	}

}

